<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 搜索模块
 *
 * @author      Eden
 * @datetime    2016/12/17 17:29
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Search_Model extends API_Model
{
    // 总数
    private $total = 0;
    private $nowPage = 1;
    const LIST_PAGE_SIZE = 20;
    protected $width = 640;
    protected $height = 360;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function run($params)
    {

        $send['state'] = false;
        do {

            if (!$this->_checkParams($params)) {
                $send['error'] = $this->getError();
                break;
            }

            $this->nowPage = !empty($params['page']) && intval($params['page']) > 0 ? intval($params['page']) : $this->nowPage;

            $res = $this->_search($params);
            $send['state'] = true;
            if (!$res) {
                $send['data'] = array(
                    'total' => 0,
                    'nextPage' => false,
                    'data' => []
                );
            } else {
                $send['data'] = array(
                    'total' => $this->total,
                    'nextPage' => $this->total > ($this->nowPage * self::LIST_PAGE_SIZE),
                    'data' => $res
                );
            }

            $this->_afterSearch($params);

        } while(false);
        $this->output->send($send);
    }

    private function _search($params = array())
    {
        $tDb = clone($this->db);
        $this->total = $tDb->where('status', 1)
            ->like('goodsName', $params['keyword'])
            ->count_all_results('base_goods');

        $db = clone($this->db);
        $q = $db->select('id, goodsName, thumb, liveUrl, thumbWidth, thumbHeight, streamId, minPrice, minPurPrice, created, expressWeight')
            ->from('base_goods')
            ->order_by('modified', 'DESC')
            ->limit(self::LIST_PAGE_SIZE, ($this->nowPage - 1) * self::LIST_PAGE_SIZE)
            ->order_by('created', 'DESC')
            ->where(array('status' => 1))
            ->like('goodsName', $params['keyword'])
            ->get();
        $rows = $q->result_array();
        if (empty($rows)){
            return [];
        }

        $results = $goodsIds = [];
        foreach($rows as $item) {
            array_push($goodsIds, $item['id']);
            $wh = $this->countWidthHeight($item['thumbWidth'], $item['thumbHeight'], $params['type']);
            $results[] = array(
                'goodsId' => intval($item['id']),
                'goodsName' => value($item, 'goodsName'),
                'thumb' => thumb($item['thumb'], $wh['width'], $wh['height']),
                'width' => $wh['width'],
                'height' => $wh['height'],
                'price' => money_format('%i', $item['minPrice'] / 100),
                'expressWeight' => doubleval($item['expressWeight']),
                'created' => formateTimeStamp($item['created']),
                'isCollected' => false,
                'isAddToCar' => false,
                'isLive' => !empty($item['liveUrl']),
                'liveUrl' => value($item, 'liveUrl', '')
            );
        }

        if (!empty($params['userId'])) {
            $collects = $this->_getCollects($params['userId'], $goodsIds);
            $cars = $this->_getCars($params['userId'], $goodsIds);
            foreach ($results as &$item) {
                $id = $item['goodsId'];
                if (!empty($collects) && in_array($id, $collects)) {
                    $item['isCollected'] = true;
                }

                if (!empty($cars) && in_array($id, $cars)) {
                    $item['isAddToCar'] = true;
                }
            }
        }
        return $results;
    }

    /**
     * After Search
     * @param array $params
     */
    private function _afterSearch($params = array())
    {
        $keyword = trim($params['keyword']);
        $q = $this->db->get_where('search', array('keyword' => $keyword));
        if ($row = $q->row_array()) {
            $this->db->where('keyword', $keyword);
            $times = intval($row['times']) + 1;
            $this->db->update('search', array('times' => $times));
        } else {
            $this->db->insert('search', array(
                'keyword' => $keyword,
                'times' => 1
            ));
        }
    }

    /**
     * 检查参数
     * @param array $params
     * @return bool
     */
    private function _checkParams($params = array())
    {
        if (empty($params['keyword'])) {
            $this->setError('缺少必填参数');
            return false;
        }

        return true;
    }
}
